package ferp.android.dialogs;

import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.widget.Button;
import ferp.android.R;

/**
 * User: olegs
 * Date: 30/05/12 22:25
 */
abstract public class YesNoDialog extends Dialog
{
  public interface Listener
  {
    void onYesClick(int requestCode);
    void onNoClick(int requestCode);
  }

  public YesNoDialog(Context context, int requestCode, int resLayout, final Listener listener)
  {
    super(context, resLayout);

    // set members
    this.requestCode = requestCode;
    this.listener = listener;

    // resolve buttons
    yes = resolveButton(R.id.dlg_element_footer_button_yes);
    no  = resolveButton(R.id.dlg_element_footer_button_no);

    // set 'yes' button listener
    yes.setOnClickListener(new View.OnClickListener()
    {
      public void onClick(View view)
      {
        if (view.isClickable())
        {
          // protect multiple clicks scenarios
          setButtonsClickableState(false);

          dismiss();
          listener.onYesClick(YesNoDialog.this.requestCode);
        }
      }
    });

    // set 'no' button listener
    no.setOnClickListener(new View.OnClickListener()
    {
      public void onClick(View view)
      {
        if (view.isClickable())
        {
          // protect multiple clicks scenarios
          setButtonsClickableState(false);

          dismiss();
          listener.onNoClick(YesNoDialog.this.requestCode);
        }
      }
    });

    setOnShowListener(new OnShowListener()
    {
      @Override
      public void onShow(DialogInterface dialogInterface)
      {
        // reset buttons clickable state
        setButtonsClickableState(true);
      }
    });
  }

  // request code
  protected final int requestCode;
  // buttons
  protected final Button yes;
  protected final Button no;
  // listener
  protected final Listener listener;

  private void setButtonsClickableState(boolean clickable)
  {
    yes.setClickable(clickable);
    no.setClickable(clickable);
  }
}
